from aqas import qp
from aqas import ir6
import re
import nltk
from socket import *
from aqas import ap
import cPickle as pickle

def init_qa(orig_query):
	(new_query,modify_list)=qp.modify_query(orig_query)
	toks=nltk.word_tokenize(new_query)
	tags=nltk.pos_tag(toks)
	#first analyze the question and find what the focus is
	focus=qp.find_question_focus(tags)
	ques_point=qp.question_point(tags)
	print 'qp= ' ,ques_point
	print 'focus=',focus
	#if ques_point=='PERSON' and focus!=None:
	#	np=focus[1].split()
	#	for j in np:
	#		for i in tags:
	#			if i[0].lower()==j.lower() and i[1]=='NN' or i[1]=='NNS':
	#				ans=ir6.search_web(orig_query,ques_point)
	#				return ans
	ans=None
	ans_flag=0
	if ques_point!="UNKNOWN":
		if ques_point=='PERSON' :
			if focus!=None:
				flag,name=qp.ques_about_person(focus[1])
				if flag==0:
					print 'no it is not ques about person'
					ans=ir6.search_web(orig_query,ques_point)
					ans_flag=1
				else:
					print 'it is ques about person'
					search_q=ir6.get_search_query(orig_query,focus)
					ans=ir6.get_descriptive_answer(search_q,name)
					ans_flag=2
			else:
				print 'no ques focus, therefore default'
				ans=ir6.search_web(orig_query,ques_point)
				ans_flag=1
		else:
			print 'default search'
			ans=ir6.search_web(orig_query,ques_point)
			ans_flag=1
		
	elif focus!=None:
		main_noun=qp.get_main_noun(focus[1])
		ques_point=qp.get_qp_from_np(main_noun)
		print 'new qp=',ques_point
		if ques_point!=None:
			ans=ir6.search_web(orig_query,ques_point)
			ans_flag=1
		elif qp.w_or_h_ques(focus[2])==1:
			print 'trying w/h'
			if qp.is_descriptive_ques(focus[1])==1:
				search_q=ir6.get_search_query(orig_query,focus)
				ans=ir6.get_descriptive_answer(search_q,'')
				ans_flag=2
	elif qp.w_or_h_ques(orig_query)==0 and qp.ques_word_present(orig_query):
		print 'trying object'
		ques_point='OBJECT'
		ans=ir6.search_web(orig_query,ques_point)
		ans_flag=1
	
	#now generate response
	
	response=ap.gen_result(ans,ques_point,orig_query,ans_flag)
	
	return response
	



HOST=''
PORT=1234
BUFSIZ=1024
ADDR=(HOST,PORT)

sock=socket(AF_INET,SOCK_STREAM)
sock.bind(ADDR)
sock.listen(5)

try:
	while True:
		print '\nWaiting for connection....'
		clisock,addr=sock.accept()
		print "\nConnection accepted from: ",addr

		#now get the query from client
		query=clisock.recv(BUFSIZ)

		#process the query now
		ans=init_qa(query)
		
		#now serialize the answer for sending...
		#serialized_ans=pickle.dumps(ans)
	
		#send it
		ret=clisock.sendall(ans.encode('ascii','ignore'))
		if ret==None:
			print 'Successfully send,%d data' % len(ans)
		else:
			print 'Error in sending '
			
		clisock.close()
except KeyboardInterrupt:
	print "\n^C pressed....server quitting!!!\n"

